<template>
  <a-card>
    <div class="operator">
      <a-button @click="addNew" type="primary">新建</a-button>
    </div>

    <a-table
      bordered
      :columns="columns"
      :data-source="dataSource"
      :loading="spinning"
      @change="handleTableChange"
      :pagination="pagination"
    >
      <div slot="action" slot-scope="record">
        <a style="margin-right: 8px" @click="editRole(record)">
          <a-icon type="edit" />编辑
        </a>
        <a @click="deleteRecord(record)"> <a-icon type="delete" />删除 </a>
      </div>

      <!-- <p slot="expandedRowRender" slot-scope="record" style="margin: 0">
              <pre>{{ record }}</pre>
            </p> -->
    </a-table>

    <a-drawer
      :title="drawertitle"
      :width="600"
      :visible="visible"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
    >
      <a-form :form="form" layout="vertical" @submit="handleSubmit">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="名称">
              <a-input
                v-decorator="[
                  'name',
                  {
                    rules: [
                      { required: true, message: 'Please enter role name' },
                    ],
                  },
                ]"
                placeholder="Please enter role name"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="描述">
              <a-textarea
                v-decorator="[
                  'description',
                  {
                    rules: [
                      {
                        required: true,
                        message: 'Please enter role description',
                      },
                    ],
                  },
                ]"
                :rows="4"
                placeholder="please enter role description"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="菜单权限">
              <a-tree-select
                v-decorator="[
                  'authority',
                  {
                    rules: [{ required: true, message: 'Please select menus' }],
                  },
                ]"
                style="width: 100%"
                :tree-data="treeMenuData"
                show-checked-strategy="SHOW_PARENT"
                tree-checkable
                search-placeholder="Please select"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <div
          :style="{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
            zIndex: 1,
          }"
        >
          <a-button :style="{ marginRight: '8px' }" @click="onClose">
            Cancel
          </a-button>
          <a-button type="primary" html-type="submit">
            Submit
          </a-button>
        </div>
      </a-form>
    </a-drawer>
  </a-card>
</template>

<script>
const columns = [
  {
    title: "编号",
    dataIndex: "Role_ID",
  },
  {
    title: "名称",
    dataIndex: "Role_Name",
  },
  {
    title: "描述",
    dataIndex: "Role_Remark",
  },
  {
    title: "是否删除",
    dataIndex: "Role_IsDelete",
  },
  {
    title: "创建时间",
    dataIndex: "Role_CreateTime",
    sorter: true,
  },
  {
    title: "操作",
    scopedSlots: { customRender: "action" },
  },
];

export default {
  data() {
    return {
      treeMenuData: [],

      advanced: true,

      visible: false,
      selectRow: null,

      dataSource: [],

      form: this.$form.createForm(this),
      drawertitle: "添加角色",

      spinning: false,
      pagination: {
        total: 20,
        title: "",
        tableName: "",
      },
      columns: columns,
    };
  },

  created: function() {
    this.loadTable("iToolBase", "Sys_Role");
    this.loadMenuTable("iToolBase", "Sys_Menu");
  },

  methods: {
    deleteRecord(row) {
      console.log(row);
      var that = this;
      this.$confirm({
        title: "Are you sure delete this role?",
        content: "删除后将从角色列表中移除",
        okText: "Yes",
        okType: "danger",
        cancelText: "No",
        onOk() {
          that.$cloud
            .invokeApiJson(
              "iToolBase",
              JSON.stringify({
                Sys_Role: {
                  Role_ID: row.Role_ID,
                },
              }),
              "remove"
            )
            .then((res) => {
              res = typeof res == "string" ? JSON.parse(res) : res;
              console.log(res);
              if (res.code == 200) {
                that.$message.success("删除成功");
                that.dataSource = that.dataSource.filter(
                  (item) => item.Role_ID !== row.Role_ID
                );
              } else {
                that.$message.error("发生错误：" + res.info);
              }
            })
            .catch((error) => {
              console.log(error);
              that.$message.error("发生错误：" + error);
            });
        },
        onCancel() {},
      });
    },

    handleTableChange(p, filters, sorter) {
      console.log(p, filters, sorter);
      this.loadTable(
        this.pagination.title,
        this.pagination.tableName,
        p.current,
        sorter.field,
        (sorter.order || "").replace("end", "")
      );
    },

    addNew() {
      this.drawertitle = "添加角色";
      this.visible = true;
      setTimeout(
        function() {
          this.form.setFieldsValue({
            name: "",
            description: "",
          });
        }.bind(this),
        200
      );
    },

    editRole(row) {
      this.selectRow = row;
      this.drawertitle = "编辑角色";
      this.visible = true;
      setTimeout(
        function() {
          this.form.setFieldsValue({
            name: row.Role_Name,
            description: row.Role_Remark,
            authority: row.RoleMenu_MenuIDs,
          });
        }.bind(this),
        200
      );
    },

    onClose() {
      this.visible = false;
      this.selectRow = null;
    },

    handleSubmit(e) {
      e.preventDefault();
      var that = this;
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);
          var where = {
            Sys_Role: {
              Role_Name: values.name,
              Role_Remark: values.description,
            },
          };

          if (that.selectRow != null) {
            where.Sys_Role.Role_ID = that.selectRow.Role_ID;
          } else {
            where.Sys_Role.Role_IsDelete = 0;
            where.Sys_Role.Role_CreateTime = new Date().Format(
              "yyyy-MM-dd HH:mm:ss"
            );
          }

          that.$cloud
            .invokeApiJson(
              "iToolBase",
              JSON.stringify(where),
              this.selectRow == null ? "register" : "modify"
            )
            .then((res) => {
              console.log(res);
              res = typeof res == "string" ? JSON.parse(res) : res;

              if (res.code == 200) {
                var roleKey = 0;
                var roleMenuKey = 0;

                if (this.selectRow == null) {
                  roleKey = res.Sys_Role.date;
                  that.dataSource.push({
                    key: res.Sys_Role.date,
                    Role_ID: res.Sys_Role.date,
                    Role_Name: values.name,
                    Role_Remark: values.description,
                    Role_IsDelete: 0,
                    Role_CreateTime: new Date().Format("yyyy-MM-dd HH:mm:ss"),
                  });
                } else {
                  roleKey = that.selectRow.Role_ID;
                  roleMenuKey = that.selectRow.RoleMenu_ID;
                  for (let index = 0; index < that.dataSource.length; index++) {
                    const element = that.dataSource[index];
                    if (element.Role_ID == that.selectRow.Role_ID) {
                      element.Role_Name = values.name;
                      element.Role_Remark = values.description;
                    }
                  }
                }

                var rolemenujson = {
                  Sys_RoleMenu: {
                    RoleMenu_MenuIDs: values.authority.join(","),
                    RoleMenu_RoleID: roleKey,
                  },
                };

                if ((roleMenuKey || 0) > 0) {
                  rolemenujson.Sys_RoleMenu.RoleMenu_ID = roleMenuKey;
                }

                that.$cloud
                  .invokeApiJson(
                    "iToolBase",
                    JSON.stringify(rolemenujson),
                    (roleMenuKey || 0) == 0 ? "register" : "modify"
                  )
                  .then((res) => {
                    res = typeof res == "string" ? JSON.parse(res) : res;

                    if (res.code == 200) {
                      if (res.Sys_RoleMenu.date > 0) {
                        console.log(res);
                        for (
                          let index = 0;
                          index < that.dataSource.length;
                          index++
                        ) {
                          const element = that.dataSource[index];
                          if (element.Role_ID == that.selectRow.Role_ID) {
                            element.RoleMenu_ID = res.Sys_RoleMenu.date;
                            element.RoleMenu_MenuIDs = values.authority;
                          }
                        }
                      } else {
                        that.$message.error("发生错误：菜单配置失败");
                      }
                    } else {
                      that.$message.error("发生错误：" + res.info);
                    }

                    that.onClose();
                  })
                  .catch((error) => {
                    that.$message.error("发生错误：" + error);
                  });

                that.$message.success(
                  this.selectRow == null ? "添加成功" : "修改成功"
                );
              } else {
                that.$message.error("发生错误：" + res.msg);
              }
            })
            .catch((error) => {
              that.$message.error("发生错误：" + error);
              console.log(error);
            });
        }
      });
    },

    loadTable(title, tableName, page, field, orderby) {
      this.spinning = true;

      this.pagination.title = title;
      this.pagination.tableName = tableName;

      var script = {};

      // script["[]"] = {
      //   count: 12,
      //   page: page ? page : 1,
      //   query: 2,
      // };

      script["[]"] = {
        Sys_Role: {},
        Sys_RoleMenu: {
          "RoleMenu_RoleID@": "/Sys_Role/Role_ID",
          "@column": "RoleMenu_ID,RoleMenu_MenuIDs",
        },
      };

      if (field) {
        script["[]"][tableName]["@order"] =
          orderby == "asc" ? field + "+" : field + "-";
      }

      script["total@"] = "/[]/total";

      this.$cloud
        .invokeApiJson("iToolBase", JSON.stringify(script), "get")
        .then((res) => {
          var data = JSON.parse(res);
          this.spinning = false;
          var tableData = data["[]"];
          this.dataSource = [];

          this.pagination.total = data.total;
          this.pagination["show-total"] = (total, range) =>
            `${range[0]}-${range[1]} of ${total} items`;
          this.pagination["pageSize"] = 12;
          this.pagination["defaultCurrent"] = 1;

          for (let index = 0; index < tableData.length; index++) {
            const row = tableData[index];
            row[tableName].key = row[tableName].Role_ID;

            if (row.Sys_RoleMenu) {
              row[tableName].RoleMenu_ID = row.Sys_RoleMenu.RoleMenu_ID;

              if (row.Sys_RoleMenu.RoleMenu_MenuIDs) {
                row[
                  tableName
                ].RoleMenu_MenuIDs = row.Sys_RoleMenu.RoleMenu_MenuIDs.split(
                  ","
                );
              } else {
                row[tableName].RoleMenu_MenuIDs = [];
              }
            }

            this.dataSource.push(row[tableName]);
          }
        });
    },

    loadMenuTable(title, tableName) {
      this.pagination.title = title;
      this.pagination.tableName = tableName;

      var script = {};

      script["[]"] = {};

      script["[]"][tableName] = {
        "@order": "Menu_Num-"
      };

      this.$cloud
        .invokeApiJson("iToolBase", JSON.stringify(script), "get")
        .then((res) => {
          var data = JSON.parse(res);
          var tableData = data["[]"];

          for (let index = 0; index < tableData.length; index++) {
            const row = tableData[index];
            if (row.Sys_Menu.Menu_ParentID - 0 < 1) {
              this.treeMenuData.push({
                value: row.Sys_Menu.Menu_ID,
                title: row.Sys_Menu.Menu_Name,
                children: [],
              });
            }
          }

          for (let index = 0; index < tableData.length; index++) {
            const row = tableData[index];
            if (row[tableName].Menu_ParentID > 0) {
              for (let index = 0; index < this.treeMenuData.length; index++) {
                const element = this.treeMenuData[index];
                if (row[tableName].Menu_ParentID == element.value)
                  element.children.push({
                    value: row.Sys_Menu.Menu_ID,
                    title: row.Sys_Menu.Menu_Name,
                  });
              }
            }
          }
        });
    },
  },
};
</script>

<style lang="less" scoped>
.search {
  margin-bottom: 54px;
}
.fold {
  width: calc(100% - 216px);
  display: inline-block;
}
.operator {
  margin-bottom: 18px;
}

.operator button {
  margin-right: 18px;
}

@media screen and (max-width: 900px) {
  .fold {
    width: 100%;
  }
}
</style>
